package pe.edu.upla.lamerced.DAO.impl;

import java.util.List;

import org.apache.log4j.Logger;
import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import pe.edu.upla.lamerced.DAO.UsuarioDAO;
import pe.edu.upla.lamerced.bean.Authorities;
import pe.edu.upla.lamerced.bean.Users;


public class UsuarioDAOImpl extends HibernateDaoSupport implements UsuarioDAO{

	private static final Logger logger = Logger.getLogger(UsuarioDAOImpl.class);
	
	public UsuarioDAOImpl(){}
	
	
	public UsuarioDAOImpl(SessionFactory sessionFactory){
		setHibernateTemplate( new HibernateTemplate(sessionFactory));
	}
	
	@Override
	public Users obtenerUsuario(Integer codigo) {
		Query query = getSession().createQuery("from Users u where username = :id  ")
        .setInteger("id", codigo);
		Users h = (Users)query.uniqueResult();
		return h;
	}

	@Override
	public Users obtenerUsuarioPorUsername(String username) {
		Query query = getSession().createQuery("from Users u where username = :id  ")
        .setString("id", username);
		Users h = (Users)query.uniqueResult();
		return h;
	}

	@Override
	public void modificarUsuario(Users us) {
		getHibernateTemplate().merge(us);
	}

	@Override
	@Transactional(propagation=Propagation.REQUIRES_NEW)
	public void registrarUsuario(Users usuario,Authorities au) {
		this.getHibernateTemplate().saveOrUpdate(usuario);
		this.getHibernateTemplate().saveOrUpdate(au);
	}

	@SuppressWarnings("unchecked")
	@Override
	@Transactional
	public List<Users> listaUsuarios() {
		Query query = getSession().createQuery("from Users where tipo=1 and enabled=1");
		return query.list();
	}
   @SuppressWarnings("unchecked")
   @Override
   @Transactional
   public List<Users> listaClientes() {
        Query query = getSession().createQuery("from Users where tipo in (2,3) and enabled=1");
		return query.list();
   }

   public Users autenticarUsuario(String username, String clave) {
      Query query = getSession().createQuery("from Users u where username = :id and password=:cla ")
        .setString("id", username)
        .setString("cla", clave);
		Users h = (Users)query.uniqueResult();
		return h;
   }

}
